package com.avidys.gwt.wom.client;

import com.avidys.common.gwt.net.ControlledWidget;
import com.avidys.common.gwt.net.Controller;
import com.avidys.common.gwt.net.Properties;
import com.avidys.common.gwt.net.JSONRPC.ServerResult;
import com.avidys.common.gwt.ui.ButtonBar;
import com.avidys.common.gwt.ui.IButtonBar;
import com.avidys.common.gwt.ui.ResultDialogBox;
import com.avidys.common.gwt.ui.iDialogOpener;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * UI for sending a ping
 * @author jm
 * TODO: externalize logPanel
 */
public class WOMPanel extends Composite implements ControlledWidget, IButtonBar {

	private static final int MAX_SLOTS = 10;
	private Controller controller;
/*			name(dropdown ip
			type(dropdown)  from freq  start %up
			last hit  last reponse time (last loading time)
			nb hits   time up    average resp time    average loading time
			CHECK NOW CHANGE HISTORY HISTOGRAM STATS 
*/
	final ListBox nameField = new ListBox(false);
	final TextBox urlField = new TextBox();
	final TextBox sentTextBox = new TextBox ();

	// Messages.mPostData
	final HTML receivedTextBox = new HTML("");
	final Label functionReceivedTextBox = new HTML("");
	final Label exceptionInfo = new Label("");

	private VerticalPanel widget;
	private ResultDialogBox dialogBox;
	private Prefs prefs=new Prefs();
	
	final private String[] buttonLabels = {Messages.mButtonNew, Messages.mButtonOptions, Messages.mButtonTest};
	final private String[] buttonRollOvers = {Messages.mRollOverButtonNew, Messages.mRollOverButtonOptions, Messages.mRollOverButtonTest};
	ButtonBar buttonBar;
	private VerticalPanel logPanel ;
	
	MyHandler handler = new MyHandler();
	Grid grid = new Grid(MAX_SLOTS,3);
	public int nbSlots=1;
	
	public WOMPanel(Prefs translated) {
		this.prefs = translated;

		if (Properties.environment==Properties.ENVIRONMENT.DEVELOPMENT) 
			buttonBar = new ButtonBar(this, buttonLabels, buttonRollOvers);
		else 
			buttonBar = new ButtonBar(this, buttonLabels, buttonRollOvers);
		
		dialogBox = new ResultDialogBox(new dialogBoxHandler());

		widget = new VerticalPanel();

		initWidget(widget);

		Label headerText = new Label(Messages.m_header);
		headerText.addStyleName("CYS-Title");
		widget.add(headerText);

		HorizontalPanel l1 = new HorizontalPanel();
		HorizontalPanel l2 = new HorizontalPanel();
		HorizontalPanel l3 = new HorizontalPanel();
		HorizontalPanel l4 = new HorizontalPanel();
		HorizontalPanel l5 = new HorizontalPanel();
		l1.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		l2.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		l3.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		l4.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		l5.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);

		nameField.addStyleName("CYS-Field");
		urlField.addStyleName("CYS-Field");

		nameField.setPixelSize(120, 20);
		urlField.setPixelSize(120, 20);

		nameField.addItem("1", "1");
		nameField.addItem("2", "2");
		nameField.addItem("3", "3");
		nameField.addItem("4", "4");
		nameField.addItem("5", "5");
		nameField.addChangeHandler(handler);
	
		//		l1.add(new Label("Please enter an URL:"));
		l1.add(nameField);
		l1.add(urlField);
		widget.add(l1);

	    updateGrid();
	    l2.add(grid);
		widget.add(l2);

		// TESTS EXT
		
//		l3.add(new DialogGames());
//		l3.add(new OnlineUsers());
//		widget.add(l3);

//		l4.add(new InfoPanel());
//		widget.add(l4);

		Label labelSend = new Label(Messages.mSent);
		l5.add(labelSend);
		l5.add(sentTextBox);
		sentTextBox.setText(Messages.mPostData);
		
		Label labelReceived = new Label(Messages.mReceived);
		l5.add(labelReceived);
		l5.add(functionReceivedTextBox);
		l5.add(receivedTextBox);
		receivedTextBox.setText(Messages.mNothingtRetrievedYet);
		
		widget.add(l5);
		// We can add style names to widgets

		exceptionInfo.addStyleName("CYS-exceptionInfo");
		widget.add(exceptionInfo);
		widget.add(buttonBar);

		logPanel = new VerticalPanel();
		logPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
		logPanel.setBorderWidth(1);
		logPanel.setHeight("300");
		logPanel.setWidth("100%");
		widget.add(logPanel);

		enableAll();
	}

    ToggleButton[] toggleButton = new ToggleButton[MAX_SLOTS];
	private void updateGrid() {
		/*
		 * on nbcol change
		 */
		for (int i = 0; i < MAX_SLOTS; i++) {
			if (i < nbSlots) {
			   //  grid.getCellFormatter().setWidth(i, 1, "256px");
			    grid.setText(i, 0, String.valueOf(i+1));
			    ToggleButton toggleButton = new ToggleButton("Up", "Down");
			    toggleButton.addClickHandler(handler);
			    grid.setWidget(i, 2, toggleButton);
			}
			else{
				grid.clearCell(i, 0);
				grid.clearCell(i, 1);
				grid.clearCell(i, 2);
			}
		}
	}

	/* 
	 * result dialogbox closing
	 */
	void enableAll() {
		dialogBox.hide();
		buttonBar.enableAll();
	}

	/*
	 * called by COntroler: add control to UIs
	 */
	public void setControllerEventHandler(EventHandler handler) {
		// buttonBar.addClickHandler((ClickHandler) handler);
		nameField.addChangeHandler((ChangeHandler) handler);
		urlField.addKeyUpHandler((KeyUpHandler) handler);
	}

	public String getTextToSent() {
		buttonBar.setEnabled(Messages.mButtonTest,false);
		String textToServer = sentTextBox.getText();
		sentTextBox.setText(textToServer);
		receivedTextBox.setText("<waiting for server>");
		return textToServer;
	}

	class dialogBoxHandler implements iDialogOpener {
		public void onDialogClose() {
			dialogBox.hide();
			buttonBar.setEnabled(Messages.mButtonTest,true);
			buttonBar.setFocus(Messages.mButtonTest,true);
		}
		public void onDialogOpen() {
		}
	}


	public void showDebugError (String error) {
		// Show the RPC error message to the user
		dialogBox.setText("Remote Procedure Call - Failure");
		dialogBox.textToServerLabel.addStyleName("receivedTextBoxError");
		dialogBox.serverResponseLabel.setHTML(error);
		dialogBox.center();
		dialogBox.closeButton.setFocus(true);
		buttonBar.setEnabled(Messages.mButtonTest,true);
	}

	public void showDebugSuccess(String result) {
		dialogBox.setText("Remote Procedure Call");
		dialogBox.serverResponseLabel.removeStyleName("receivedTextBoxError");
		dialogBox.serverResponseLabel.setHTML(result);
		dialogBox.center();
		dialogBox.closeButton.setFocus(true);
		buttonBar.setEnabled(Messages.mButtonTest,true);
	}

	public void onTextReceived(String function, String response) {
		functionReceivedTextBox.setText(function);
		receivedTextBox.setText(response);
		buttonBar.setEnabled(Messages.mButtonTest,true);
		log(function+" -> "+response);
	}

	private void log(String string) {
		logPanel.add(new HTML(string));
	};

	public void onLogicError(String error) {
		Window.alert("RPC Failed: " + error);
		exceptionInfo.setText(Messages.mErrorLogic+" "+error);
		buttonBar.setEnabled(Messages.mButtonTest,true);
	}

	public void onRPCError(Throwable caught) {
		Window.alert("RPC Failed: " + caught);
		exceptionInfo.setText(Messages.mErrorRPC+" "+caught.toString());
		buttonBar.setEnabled(Messages.mButtonTest,true);
	}

	public void setController(Controller controller) {
		this.controller = controller;
		// done by controller this.setEventHandler(controller.getEventHandler());
	}

	// Create a handler for the sendButton and nameField
	class MyHandler implements ClickHandler, KeyUpHandler, ChangeHandler {
		/**
		 * Fired when the user clicks on the sendButton.
		 */
		Button lastButtonClicked ;

		public void onClick(ClickEvent event) {
			ToggleButton s = (ToggleButton) event.getSource();
			log("Click " + event.toDebugString());
//			lastButtonClicked = s;
//			int i = buttonBar. whichBUTTON(s);
			int i=getToggleButtonPos(s);
//			if (i>-1) send
			// when receive from sevrer: actually toggle
		}

		public void onKeyUp(KeyUpEvent event) {
		}

		public void onChange(ChangeEvent event) {
			String s = nameField.getValue(nameField.getSelectedIndex());
			int i = Integer.parseInt(s);
			if (i != -1) nbSlots=i;
			updateGrid();
			String[][] e = {{"slots",s},};
			//e[0][0]="slots";
			//e[0][1]=s;
			controller.sendTextToServer("setNbSlots", "WOMPanel", e);
		}

	}

	public int getToggleButtonPos(ToggleButton s) {
		for (int i = 0; i < nbSlots; i++) {
			if (s.equals(grid.getWidget(i, 2))) return i;	
		}
		return -1;
	}


	public void onButtonClicked(int lastButtonClickedInt,
			Button lastButtonClicked) {
		switch (lastButtonClickedInt) {
		case 0:
			controller.sendTextToServer("start", getTextToSent(), lastButtonClicked.getElement().getId());
			break;
		case 1:
			controller.sendTextToServer("getTime", getTextToSent(), lastButtonClicked.getElement().getId());
			break;
		case 2:
			controller.sendTextToServer("add", getTextToSent(), lastButtonClicked.getElement().getId());
			break;
		default:
		}
	}

	@Override
	public void onTextReceived(ServerResult[] r) {
		// TODO Auto-generated method stub
		
	}
}